package primary_classes;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import secondary_classes.CsvFileReader;
import _runnable_classes.TradingEngine;



/**
 * @author Rohit
 *
 */
public class SystemVars {
	
	public  static enum STATUS {OK, ERR};
	
	private static final String[] ITEMS = {"input_file", "input_file_dir", "output_file_dir", "marketDepthSize"};
	
	private static String inputFilename;
	private static String outputFilename;
	
	private static File inputFile;
	private static File inputFileDir;
	private static File outputFileDir;
	
	private static int marketDepthSize;
	
	private static File marketDepthFile;
	private static File tradesFile;
	private static File logFile;
	private static File tradesComparatorFile;
	
	public SystemVars(String inputFile, String inputDir, String outputFile, String outputFileDir, int marketDepthSize) {
		SystemVars.inputFilename = inputFile;
		SystemVars.outputFilename = outputFile;
		
		SystemVars.inputFile = new File(inputFilename);
		SystemVars.inputFileDir = new File(inputDir);
		SystemVars.outputFileDir = new File(outputFileDir);
		
		SystemVars.marketDepthSize = marketDepthSize;
		
		String outputPath = SystemVars.outputFileDir.getAbsolutePath();
		String filenameNoExt = outputPath + File.separator + SystemVars.inputFile.getName().substring(0, SystemVars.inputFile.getName().length() - 4);
		SystemVars.marketDepthFile = new File(filenameNoExt + "_ob.csv");
		SystemVars.tradesFile = new File(filenameNoExt + "_tr.csv");
		SystemVars.logFile = (new File(filenameNoExt + "_log.txt"));
		SystemVars.tradesComparatorFile = (new File(filenameNoExt + "_tradescomp.txt"));
		
		if (!SystemVars.inputFileDir.getPath().equals("")) {
			SystemVars.inputFile = new File(SystemVars.inputFileDir + File.separator + SystemVars.inputFile);
		}
	}
	
	/**
	 * Manages information about System Variables.
	 * @param inputFileString The input file in CSV format
	 * @param outputFile where a generated output file should go
	 * @throws Exception use {@link Exception#getMessage()} to get a more detailed explanation
	 */
	public SystemVars(String inputFileString, String outputFile) throws Exception {
		inputFilename = inputFileString;
		outputFilename = outputFile;
		
		// read in CSV file
		CsvFileReader cfr = new CsvFileReader(inputFilename);
		
		if (cfr.getNumLines() != ITEMS.length) {
			throw new Exception("Invalid system variables file (incorrect number of fields): " + inputFilename);
		}
		
		for (int i = 0; i < ITEMS.length; i++) {
			String currentAttribute = cfr.getItem(i, 0);
			String currentValue = cfr.getItem(i, 1);
			if (currentValue == null) {
				currentValue = "";
			}
			
			if (currentAttribute.equals(ITEMS[0])) {
				inputFile = new File(currentValue);
			} else if (currentAttribute.equals(ITEMS[1])) {
				inputFileDir = new File(currentValue);
			} else if (currentAttribute.equals(ITEMS[2])) {
				outputFileDir = new File(currentValue);
			} else if (currentAttribute.equals(ITEMS[3])) {
				marketDepthSize = Integer.valueOf(currentValue);
				String outputPath = outputFileDir.getAbsolutePath();
				if (!outputPath.equals("")) {
					outputPath += File.separator;
				}
				
			} 
//			else if (currentAttribute.equals(ITEMS[4])) {
//				int j;
//				if ((j = PhaseStrings.indexOf(currentValue)) != -1) {
//					marketPhase = PHASE.values()[j];
//				} else {
//					throw new Exception("Invalid system variables file " +
//							"(incorrect value for \"marketPhase\" field): " + inputFilename);
//				}
//			}
			
		}
		
		String outputPath = outputFileDir.getAbsolutePath();
		String filenameNoExt = outputPath + File.separator + inputFile.getName().substring(0, inputFile.getName().length() - 4);
		marketDepthFile = new File(filenameNoExt + "_ob.csv");
		tradesFile = new File(filenameNoExt + "_tr.csv");
		logFile = (new File(filenameNoExt + "_log.txt"));
		tradesComparatorFile = (new File(filenameNoExt + "_tradescomp.txt"));
		
		if (!inputFileDir.getPath().equals("")) {
			inputFile = new File(inputFileDir + File.separator + inputFile);
		}

	}
	
	/**
	 * Generates an output file
	 * @param s Can be either {@link STATUS#OK} or {@link STATUS#ERR} - if there is an error, an error message must also be supplied
	 * @param errorMessage The message if there is an error.  This is ignored if the status is not {@link STATUS#ERR}
	 */
	public static void generateStatusFile(STATUS s, String errorMessage) {
		System.out.print(TradingEngine.elapsedTimeString() + "  WRITING STATUS FILE                                               \r");
		String outputPath;
		try {
			outputPath = outputFileDir.getAbsolutePath();
		} catch (NullPointerException e) {
			outputPath = "";
		}
		if (!outputPath.equals("")) {
			outputPath += File.separator;
		}
		outputPath += outputFilename;
		
		BufferedWriter writer;
		File outputFile = new File(outputPath);
		try {
			writer = new BufferedWriter(new FileWriter(outputFile));
			if (s.equals(STATUS.OK)) {
				writer.write("OK");
				writer.newLine();
				writer.append(inputFile.getAbsolutePath());
				writer.close();
			} else if (s.equals(STATUS.ERR)) {
				writer.write("ERR");
				writer.newLine();
				writer.append(errorMessage);
				writer.close();
			}
			System.out.println(TradingEngine.elapsedTimeString() + "  WRITING STATUS FILE - Done                                        ");
		} catch (Exception e) {
			String err = "Could not write to file: " + outputFilename;
			System.out.println(err);
		}
		System.exit(0);
	}
	
	public static File getInputFile() {
		return inputFile;
	}
	
	public static File getInputFileDir() {
		return inputFileDir;
	}
	
	public static File getOutputFileDir() {
		return outputFileDir;
	}

	/**
	 * @return the marketDepthFile
	 */
	public static File getMarketDepthFile() {
		return marketDepthFile;
	}

	/**
	 * @return the marketDepthSize
	 */
	public static int getMarketDepthSize() {
		return marketDepthSize;
	}

	public static File getTradesFile() {
		return tradesFile;
	}

	public static File getLogFile() {
		return logFile;
	}

	public static File getTradesComparatorFile() {
		return tradesComparatorFile;
	}

}
